package com.chinatechstar.component.commons.utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.StringReader;
import java.util.*;

/**
 * XML解析工具类
 */
public class XmlUtils {

    /**
     * 解析XML字符串为Map，支持xml标签多层嵌套，并以"."分隔多级标签（不包括根节点）。不支持XML标签重复时的情况
     *
     * @param xml XML字符串
     * @param map Map
     * @return Map<String, String>
     */
    public static Map<String, String> parseXml2Map(String xml, Map<String, String> map) {
        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read(new StringReader(xml));
            Element root = doc.getRootElement();
            String path = "";
            if (map.containsKey(root.getName().trim())) {
                path = map.get(root.getName().trim());
                map.remove(root.getName().trim());
            }
            for (Iterator i = root.elementIterator(); i.hasNext(); ) {
                Element element = (Element) i.next();
                if (element.isTextOnly()) {
                    if (path.length() > 0) {
                        map.put(path + element.getName().trim(), element.getTextTrim());
                    } else {
                        map.put(element.getName().trim(), element.getTextTrim());
                    }
                } else {
                    map.put(element.getName().trim(), path + element.getName().trim() + ".");
                    parseXml2Map(element.asXML(), map);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * 解析A2 XML字符串为List。
     *
     * @param xml XML字符串
     * @return Map<String, String>
     */
    public static List<Map<String, String>> parseA2Xml2Map(String xml, String[] fields) {
        List<Map<String, String>> list = new ArrayList<>();
        if (fields.length <= 0) {
            return list;
        }

        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read(new StringReader(xml));
            Element root = doc.getRootElement();

            // 必须按层级取数据，否则查询失败
            Iterator targetRoot = root.elementIterator("diffgram");

            if (targetRoot.hasNext()) {
                Element next = (Element) targetRoot.next();
                Iterator docRoot = next.elementIterator("DocumentElement");
                if (docRoot.hasNext()) {
                    Element docElement = (Element) docRoot.next();
                    Map<String, String> tempMap;

                    // 遍历实际数据节点
                    for (Iterator i = docElement.elementIterator("data"); i.hasNext(); ) {
                        tempMap = new HashMap<>();
                        Element data = (Element) i.next();
                        for (String field : fields) {
                            tempMap.put(field, data.elementTextTrim(field));
                        }
                        list.add(tempMap);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 解析XML字符串
     *
     * @param xml XML字符串
     */
    public static void readStringXml(String xml) {
        Document doc;
        try {

            // 读取并解析XML文档
            // SAXReader就是一个管道，用一个流的方式，把xml文件读出来
            //
            // SAXReader reader = new SAXReader(); //User.hbm.xml表示你要解析的xml文档
            // Document document = reader.read(new File("User.hbm.xml"));
            // 下面的是通过解析xml字符串的
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML

            Element rootElt = doc.getRootElement(); // 获取根节点
            System.out.println("根节点：" + rootElt.getName()); // 拿到根节点的名称

            Iterator iter = rootElt.elementIterator("head"); // 获取根节点下的子节点head，这里的head就是上面打印出来的根节点的名称

            // 遍历head节点
            while (iter.hasNext()) {

                Element recordEle = (Element) iter.next();
                String title = recordEle.elementTextTrim("title"); // 拿到head节点下的子节点title值，这里同样也是需要head下存在这个title节点
                System.out.println("title:" + title);

                Iterator iters = recordEle.elementIterator("script"); // 获取子节点head下的子节点script

                // 遍历Header节点下的Response节点
                while (iters.hasNext()) {

                    Element itemEle = (Element) iters.next();

                    String username = itemEle.elementTextTrim("username"); // 拿到head下的子节点script下的字节点username的值
                    String password = itemEle.elementTextTrim("password");

                    System.out.println("username:" + username);
                    System.out.println("password:" + password);
                }
            }
            // 获取根节点下的子节点body，这里看报文，有的报文可能叫Body大写字段开头
            Iterator iterss = rootElt.elementIterator("body");

            // 遍历body节点
            while (iterss.hasNext()) {

                Element recordEless = (Element) iterss.next();
                String result = recordEless.elementTextTrim("result"); // 拿到body节点下的子节点result值
                System.out.println("result:" + result);

                Iterator itersElIterator = recordEless.elementIterator("form"); // 获取子节点body下的子节点form
                // 遍历Header节点下的Response节点
                while (itersElIterator.hasNext()) {

                    Element itemEle = (Element) itersElIterator.next();

                    String banlce = itemEle.elementTextTrim("banlce"); // 拿到body下的子节点form下的字节点banlce的值
                    String subID = itemEle.elementTextTrim("subID");

                    System.out.println("banlce:" + banlce);
                    System.out.println("subID:" + subID);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 将xml字符串转换成map
     *
     * @param xml XML字符串
     * @return Map
     */
    public static Map<String, String> readStringXmlOut(String xml) {
        Map<String, String> map = new HashMap<>();
        Document doc;
        try {
            // 将字符串转为XML
            doc = DocumentHelper.parseText(xml);
            // 获取根节点
            Element rootElt = doc.getRootElement();
            // 拿到根节点的名称
            System.out.println("根节点：" + rootElt.getName());

            // 获取根节点下的子节点head
            Iterator iter = rootElt.elementIterator("DataTable");
            // 遍历head节点
            while (iter.hasNext()) {

                Element recordEle = (Element) iter.next();
                // 拿到head节点下的子节点title值
                String title = recordEle.elementTextTrim("title");
                System.out.println("title:" + title);
                map.put("title", title);
                // 获取子节点head下的子节点script
                Iterator iters = recordEle.elementIterator("script");
                // 遍历Header节点下的Response节点
                while (iters.hasNext()) {
                    Element itemEle = (Element) iters.next();
                    // 拿到head下的子节点script下的字节点username的值
                    String username = itemEle.elementTextTrim("username");
                    String password = itemEle.elementTextTrim("password");

                    System.out.println("username:" + username);
                    System.out.println("password:" + password);
                    map.put("username", username);
                    map.put("password", password);
                }
            }

            // 获取根节点下的子节点body
            Iterator iterss = rootElt.elementIterator("body");
            // 遍历body节点
            while (iterss.hasNext()) {
                Element recordEless = (Element) iterss.next();
                // 拿到body节点下的子节点result值
                String result = recordEless.elementTextTrim("result");
                System.out.println("result:" + result);
                // 获取子节点body下的子节点form
                Iterator itersElIterator = recordEless.elementIterator("form");
                // 遍历Header节点下的Response节点
                while (itersElIterator.hasNext()) {
                    Element itemEle = (Element) itersElIterator.next();
                    // 拿到body下的子节点form下的字节点banlce的值
                    String banlce = itemEle.elementTextTrim("banlce");
                    String subID = itemEle.elementTextTrim("subID");
                    System.out.println("banlce:" + banlce);
                    System.out.println("subID:" + subID);
                    map.put("result", result);
                    map.put("banlce", banlce);
                    map.put("subID", subID);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

}
